<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Chat</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        #chat-box {
            width: 400px;
            height: 500px;
            border: 1px solid #ccc;
            padding: 10px;
            overflow-y: auto;
            margin-bottom: 10px;
        }
        #user-input {
            width: 300px;
            padding: 5px;
        }
        #send-btn {
            padding: 5px 10px;
        }
    </style>
</head>
<body>
    <h1>与大模型对话</h1>
    <div id="chat-box"></div>
    <input type="text" id="user-input" placeholder="输入你的问题...">
    <button id="send-btn">发送</button>

    <script>
        let messages = [];  // 存储对话上下文

        document.getElementById('send-btn').addEventListener('click', async () => {
            const userInput = document.getElementById('user-input').value;
            if (!userInput) return;

            // 显示用户输入
            document.getElementById('chat-box').innerHTML += `<p><strong>你:</strong> ${userInput}</p>`;
            document.getElementById('user-input').value = '';

            // 发送请求到服务器
            const response = await fetch('/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ message: userInput, messages: messages }),
            });

            const data = await response.json();
            if (data.response === "对话已结束，历史记录已保存。") {
                alert(data.response);
                return;
            }

            // 显示 AI 的响应
            document.getElementById('chat-box').innerHTML += `<p><strong>AI:</strong> ${data.response}</p>`;
            messages = data.messages;  // 更新上下文
        });
    </script>
</body>
</html>